package managers
{
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.utils.ObjectProxy;
	import vos.RSSItem;
	
	public class FeedParser extends EventDispatcher
	{		
		private const CHANGE_EVENT:String = "feedHelperChange";
		
		private var _feedItems:ArrayCollection;
		private var _feedTitle:String;
		private var _feedImage:String;
		
		[Bindable(event = CHANGE_EVENT)]
		public function get feedImage():String
		{
			return _feedImage;
		}

		[Bindable(event = CHANGE_EVENT)]
		public function get feedTitle():String
		{
			return _feedTitle;
		}

		[Bindable(event = CHANGE_EVENT)]
		public function get feedItems():ArrayCollection
		{
			return _feedItems;
		}

		public function FeedParser():void
		{
			_feedItems = new ArrayCollection;
		}
		
		public function parseFeed(feed:ObjectProxy):void
		{			
			_feedTitle = feed.rss.channel.title;
			_feedImage = feed.rss.channel.image.url;
			
			/* Iterate over all the items in the channel */
			for each (var currentItem:Object in feed.rss.channel.item) 
			{
				/* Construct the new RSS item from the XML data */
				var newRSSItem:RSSItem = new RSSItem();
				newRSSItem.author = currentItem.author;
				newRSSItem.description = currentItem.description;
				newRSSItem.link = currentItem.link;
				newRSSItem.pubDate = currentItem.pubDate;
				newRSSItem.title = currentItem.title;
				
				/* Make an array of all the pictures (extracted from the <img> tags) */
				newRSSItem.pictures = new ArrayCollection();
				var tmpXML:XML = new XML('<p>' + newRSSItem.description + '</p>');
				for each(var img:XML in tmpXML.img)
				newRSSItem.pictures.addItem(String(img.@src));
				
				_feedItems.addItem(newRSSItem);
			}
			dispatchEvent(new Event(CHANGE_EVENT));
		}
	}
}